package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import com.mjk.common.web.getway.utils.BeeRoleUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.regex.Pattern;

/**
 * 鉴权
 * @author mjk
 *
 */
@BeeGetWayInterceptor(value=4,interceptorType={GetWayInterceptorType.ALL})
@ConditionalOnProperty(name="bee.header.auth",havingValue="true")
public class GetWayAuthInterceptor implements GetWayInterceptor {

	//定义不进行 头部鉴权的 URL
	private final String[] notCheckUrl = new String[]{"/ld.*/machine", "/ld.*/soap"};
	@Override
	public BeeResponse interceptor(GetWayInterceptorReq request,
								   InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
		boolean isCheck = true;
		if(null == request.getRequest()) {//如果不是http请求
			return next.proceed(request);
		}
		//如果是登入接口，则不效应
		String method = MapUtils.getString(request.getParams(), GetwayConsts.METHOD);
		if (method.equalsIgnoreCase("login")) {
			isCheck = false;
		}
		String url = request.getRequest().getRequestURI();
		for(String checkUrl : notCheckUrl){
			if(Pattern.matches(checkUrl, url)){
				isCheck = false;
			}
		}
		//如果是apipost请求放行
//		if(GetwayConsts.API_POST_USER_AGENT.equals(MapUtils.getString(request.getHeadParams(),GetwayConsts.USER_AGENT))){
//			isCheck = false;
//		}

		if(isCheck){
			//如果不是登入状态
			if (!StpUtil.isLogin()) {
				return BeeError.TOKEN_IS_NOT_EXIT.tranceError();
			}

			//获取登入用户名
			Object obj = StpUtil.getLoginId();
			request.getParams().put("oper", ObjectUtils.isEmpty(obj) ? "" : obj.toString());
		}
		return next.proceed(request);
	}

}
